package redis.lock.common.lock.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;
import redis.lock.common.lock.annotation.BFLock;
import redis.lock.common.lock.dto.BFLockModel;
import redis.lock.common.lock.dto.BFLockModelProvider;

/**
 * BFLock aspect
 * @author zhenglian
 */
@Slf4j
@Aspect
@Order(0)
@Component
public class BFLockAspectHandler {

    /**
     * 切点
     */
    @Pointcut("@annotation(redis.lock.common.lock.annotation.BFLock)")
    private void bfLockPointCut() {
    }

    /**
     *
     * @param joinPoint 切入点
     * @return
     */
    @Before("bfLockPointCut()")
    private Object before(JoinPoint joinPoint) {
        BFLock bfLock = getBFLock(joinPoint);
        BFLockModel bfLockModel = BFLockModelProvider.getInstence(bfLock);

        return null;
    }

    /**
     * 获取 BFLock 注解
     * @param joinPoint 接入点
     * @return
     */
    private BFLock getBFLock(JoinPoint joinPoint) {
        BFLock bfLock = null;
        // 获取该接入点所在的类
        Class<?> jClass = joinPoint.getTarget().getClass();
        // 获取该接入点锁在的方法
        String methodName = joinPoint.getSignature().getName();
        // 获取具体的方法对象
        try {
            Method method = jClass.getMethod(methodName);
            // 获取BFLock注解
            bfLock = method.getAnnotation(BFLock.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        return bfLock;
    }

}
